<template>
  <div class="h100 commonTableSty" style="padding:40px" ref="configEcuTableList">
    <s-table
      class="h100"
      :components="tableComponents"
      :columns="columns"
      :loading="loadingTbData"
      :dataSource="dataList"
      :pagination="false"
      :rowKey="(record) => record.id"
      :showFilter="false"
    >
      <!-- 自定义依赖分组列 -->
      <span slot="dependentGroupingColumn">
        {{ $t('dependentGrouping') }}
        <question-mark-tip
          :tip-title="$t('dependentGroupingColumnTip')"
          :popupContainer="getPopupContainerColumn"
        ></question-mark-tip>
      </span>
      <!-- 自定义是否回滚列 -->
      <!-- <span slot="isRollbackColumn">
        {{ $t('isRollback') }}
        <question-mark-tip
          :tip-title="$t('isRollbackColumnTip')"
          :popupContainer="getPopupContainerColumn"
        ></question-mark-tip>
      </span> -->
      <!-- 自定义升级顺序列 -->
      <span slot="updateOrderColumn">
        {{ $t('updateOrder') }}
        <question-mark-tip
          :tip-title="$t('updateOrderColumnTip')"
          :popupContainer="getPopupContainerColumn"
        ></question-mark-tip>
      </span>
      <template slot-scope="text" v-for="column in commonColumns" :slot="column.scopedSlots.customRender">
        <table-ellipsis :text="text || '-'" :key="column.dataIndex"></table-ellipsis>
      </template>
      <template slot="dependentGrouping" slot-scope="text, record">
        <a-input-number :min="1" :max="999" :precision="0" v-model="record.form.groupNo" v-if="!!record.form.editing" :disabled="record.form.disabled"/>
        <span v-else>{{record.groupNo}}</span>
      </template>
      <template slot="updateOrder" slot-scope="text, record">
        <a-input-number :min="1" :max="999" :precision="0" v-model="record.form.groupUpgradeNo" v-if="!!record.form.editing" />

        <span v-else>{{record.groupUpgradeNo}}</span>
      </template>
      <template slot="vinList" slot-scope="text, record">
        <a-button :min="1" v-if="record.form.ecuAssembleType === 2" @click="() => {currentEcuModuleId = record.ecuModuleId;importVisible= true}">导入</a-button>
        <span v-else-if="record.form.ecuAssembleType === 1">全部</span>
        <span v-else>无</span>
      </template>
      <template slot="isRollback" slot-scope="text, record">
        <rollback-select
          style="width:100%"  :disabled="record.form.disabled"
          :defaultValue="typeof record.form.groupRollback !== 'undefined' ? Number(record.form.groupRollback): undefined"
          @changeoption="handleSelectRollback($event, record)"
          v-if="!!record.form.editing"
        ></rollback-select>
        <span v-else>{{record.groupRollback === true ? $t('rollbackYes') : (record.groupRollback === false ? $t('rollbackNo') : '')}}</span>
      </template>
      <template slot="ecuAssembleType" slot-scope="text,record">
<!--        <a-select v-if="!!record.form.editing"-->
<!--          :placeholder="$t('ecuAssembleType')" @change="changeAssembleType($event, record)"-->
<!--          v-model="record.form.ecuAssembleType" style="width: 100%">-->
<!--          <a-select-option v-for="item in $store.state.dict.ecuAssembleTypeOptions" :key="item.id" :value="item.value">-->
<!--            {{ $t(item.name) }}-->
<!--          </a-select-option>-->
<!--        </a-select>-->
<!--        <span v-else>{{$t($store.getters.getDictCodeObj('ecuAssembleTypeOptions')[record.ecuAssembleType])}}</span>-->
        <span>{{$t($store.getters.getDictCodeObj('ecuAssembleTypeOptions')[record.ecuAssembleType])}}</span>
      </template>
      <span
        slot="action"
        slot-scope="text, record"
        class="tableOperateSty"
      >
        <auth-button type="primary" :ghost="true" size="small" :auth="managePerms.model.edit" v-if="!record.form.editing" @click="record.form.editing=true">
          <i class="iconfont icon-xiugai"/>{{ $t('edit') }}
        </auth-button>
        <a-tooltip :title="$t('save')" v-if="record.form.editing">
          <auth-text type="default" :auth="managePerms.model.edit" @click="updateRow(record)"
                     style="margin-right: 10px">
            <a-icon type="check" :style="{ color: 'green' }"/>
          </auth-text>
        </a-tooltip>
        <a-tooltip :title="$t('cancel')" v-if="record.form.editing">
          <a-button type="link" @click="record.form.editing=false">
            <a-icon type="close" :style="{ color: 'red' }"/>
          </a-button>
        </a-tooltip>
      </span>
    </s-table>
    <import-ecu-vins v-model="importVisible" :cols="importCols" :ecuModuleId="currentEcuModuleId"/>
  </div>
</template>
<script>
import { configEcuColum } from '../config/list'
import tableDraggable from '@/utils/tableDraggable'
import RollbackSelect from '@/views/components/RollbackSelect'
import QuestionMarkTip from '@/views/components/QuestionMarkTip'
import { mapState } from 'vuex'
import tableEllipsis from '@/components/Ellipsis/TableEllipsis'
import { managePerms } from '@/config/permission/index'
import AuthText from '@/components/AuthText'
import ImportEcuVins from "./ecu/ImportEcuVins";
import { STable } from '@/components'
import AuthButton from '@/components/AuthButton'
const initConfig = {
  groupUpgradeNo:  '',
  groupNo: '',
  groupRollback: '',
  ecuAssembleType: '',
};
export default {
  name: 'ConfigEcu',
  components: {
    RollbackSelect,
    QuestionMarkTip,
    ImportEcuVins,
    AuthText,
    STable,
    tableEllipsis,
    AuthButton
  },
  props: {
    recordData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  computed: {
    ...mapState({
      newModelData: state => state.model.newModelData,
      instantUpdateTime: (state) => state.app.instantUpdateTime
    }),
    commonColumns () {
      return this.columns.filter(item => !item.special)
    }
  },
  data () {
    return {
      importVisible: false,
      currentEcuModuleId: '',
      columns: configEcuColum,
      loadingTbData: false,
      managePerms,
      dataList: [],
      importCols : [{
        title: 'VIN',
        dataIndex: 'vin',
        width: '200',
        scopedSlots: { customRender: 'vin' }
      }]
    }
  },
  watch: {
  },
  created () {
    this.tableComponents = tableDraggable(this.columns)
    this.getData();
  },
  methods: {
    getPopupContainerColumn () {
      return document.body
    },
    changeAssembleType(val, record) {
      if (val === 0) {
        record.form.disabled = true;
        // record.form.groupUpgradeNo = '';
        // record.form.groupNo = '';
        // record.form.groupRollback = '';
      } else {
        record.form.disabled = false;
        // record.form.groupUpgradeNo = record.groupUpgradeNo;
        // record.form.groupNo = record.groupNo;
        // record.form.groupRollback = record.groupRollback;
      }
    },
    // 选择回滚
    handleSelectRollback (data, record) {
      if (data === 1) {
        record.form.groupRollback = true;
      }else if (data === 0) {
        record.form.groupRollback = false;
      } else {
        record.form.groupRollback = undefined;
      }
    },
    getData () {
      const vm = this
      // vm.$api.getEcuList({ modelId: this.recordData.id }).then((ecus) => {
        vm.$api.getConfigEcuList({ id: vm.recordData.id }).then((res) => {
          let ecuModuleIds = [];
          if (res.data) {
            res.data.forEach((item) => {
              ecuModuleIds.push(item.ecuModuleId)
              item.form = {
                editing : false,
                disabled : item.ecuAssembleType === 0,
                groupUpgradeNo: item.groupUpgradeNo,
                groupNo: item.groupNo,
                groupRollback: item.groupRollback,
                ecuAssembleType: item.ecuAssembleType,
              }
            });
          }
          // ecus.data.filter(item => ecuModuleIds.indexOf(item.ecuModuleId) >= 0).forEach(item => {
          //   res.data.push({
          //     code: item.code,
          //     modelId: item.id,
          //     name: item.name,
          //     form : {
          //       editing : false,
          //       disabled : true,
          //       groupUpgradeNo: undefined,
          //       groupNo: undefined,
          //       groupRollback: undefined,
          //       ecuAssembleType: 0,
          //     }
          //   })
          // });
          vm.dataList = res.data.map(item =>{
            return Object.assign({},initConfig, item);
          })
        })
      // })

    },
    updateRow(record) {
      if (record.form.ecuAssembleType === 0) {
        this.deleteModelEcu(record);
        return
      }
      this.$api.editModelEcuConfig({
        id: record.id,
        groupNo: record.form.groupNo,
        groupUpgradeNo: record.form.groupUpgradeNo,
        groupRollback: record.form.groupRollback,
        ecuAssembleType: record.form.ecuAssembleType,
      }).then(() =>{
        this.$message.success(this.$t('successfullyOperation'))
        record.form.editing = false;
        this.$api.getConfigEcuList({ id: this.recordData.id }).then((res) => {
            //找到这一条覆盖
          let target = this.dataList.find(item => item.id==record.id);
          Object.assign(target, initConfig, {...res.data.find(item => item.id==record.id)});
          });
      });
    },
    // 删除款型ECU配置
    deleteModelEcu (record) {
      const vm = this;
      this.$confirm({
        title: vm.$t('提示'),
        content: vm.$t('配置为无，确定该款型不需要此ECU吗？'),
        class: 'confirmStyle',
        icon: '<Icon >',
        width: 378,
        onOk () {
          vm.$api.delModelEcuConfig(record.id).then(response => {
            vm.$message.success(vm.$t('successfullyOperation'))
            vm.getData() // 刷新页面
          });
        },
        onCancel () { }
      })
    },
    // getFormData () {
    //   const vm = this
    //   return new Promise((resolve) => {
    //     const ecuVersions = []
    //     vm.dataList.forEach(item => {
    //       const { id, groupUpgradeNo, groupRollback, groupNo } = item
    //       ecuVersions.push({
    //         id,
    //         groupUpgradeNo,
    //         groupRollback,
    //         groupNo
    //       })
    //     })
    //     const params = {
    //       ecuVersions,
    //       configTag: true
    //     }
    //     resolve(params)
    //   })
    // }
  }
}
</script>
